<template>
    <div class="main_info">
        <header>
            <div class="rule_section">
                <div class="rule_item--wrap" :class="{ active: chooseRuleId === null }" @click="chooseRuleId = null">
                    {{ $t('button.baseRule') }}
                </div>
                <div class="rule_item--wrap" v-for="(rule, index) in ruleList" :key="rule.id"
                    :class="{ active: chooseRuleId === rule.id }">
                    <p @click="chooseRuleId = rule.id">{{ rule.name }}</p>
                    <n-icon :size="14" color="#f40" @click="handleDeleteRule(rule.id, index)">
                        <TrashSharp />
                    </n-icon>
                </div>
            </div>
            <n-button-group>
                <n-button strong secondary @click="openNewRuleModal" size="small">
                    <template #icon>
                        <n-icon :size="16">
                            <Add />
                        </n-icon>
                    </template>
                    {{ $t('button.custom') }}
                </n-button>
                <n-button strong secondary type="primary" @click="useRulesMessage" size="small">
                    <template #icon>
                        <n-icon>
                            <ColorWandSharp />
                        </n-icon>
                    </template>
                    {{ $t('button.useRule') }}
                </n-button>
                <n-button @click="router.back()" size="small">
                    <template #icon>
                        <n-icon>
                            <ChevronBackOutline />
                        </n-icon>
                    </template>
                    {{ $t('button.returnBack') }}
                </n-button>
            </n-button-group>
        </header>
        <section class="rule_setting">
            <n-tabs type="card" animated v-model:value="chooseBo" size="small" :addable="!disForm" :closable="!disForm"
                @add="addNewTab" @close="closeTab">
                <n-tab-pane v-for="item in stepBoArray" :name="item.label" :tab="item.value">
                    <n-card class="card_container">
                        <n-alert title="规则配置说明" type="warning">
                            <p>这边进行规则配置后，需要先<span class="high-light">保存规则</span>，再点击<span
                                    class="high-light">使用规则</span>，这里配置的规则方可生效。<span class="high-light">默认规则无法修改</span>。
                            </p>
                            <p>注意：最多只能开启<span class="high-light">7</span>个ban位，最多只能开启<span
                                    class="high-light">3/9</span>个全局ban位，且前面轮次选过的图，在后续选图中无法选择，请谨慎配置规则。</p>
                            <p>若更新版本后发现规则不可用，<span class="high-light">可以删除规则重新配置。</span></p>
                        </n-alert>
                        <n-form style="margin-top: 0.5em;" :model="boStepConfig[item.label]" size="small"
                            label-placement="top">
                            <n-grid :cols="24" :x-gap="24">
                                <n-form-item-gi :span="12" :label="$t('label.allowBanMap')" path="title">
                                    <n-switch v-model:value="boStepConfig[item.label].banMap" :disabled="disForm">
                                        <template #checked>
                                            允许禁图
                                        </template>
                                        <template #unchecked>
                                            不禁图
                                        </template>
                                    </n-switch>
                                </n-form-item-gi>
                                <n-form-item-gi :span="12" :label="$t('label.allowChooseMap')" path="title">
                                    <n-switch v-model:value="boStepConfig[item.label].chooseMap" :disabled="disForm">
                                        <template #checked>
                                            重选图
                                        </template>
                                        <template #unchecked>
                                            延续上轮图
                                        </template>
                                    </n-switch>
                                </n-form-item-gi>
                            </n-grid>
                            <n-grid :cols="24" :x-gap="24">
                                <n-form-item-gi :span="12" :label="$t('label.hunterBanNumber')" path="title">
                                    <div class="count_container">
                                        <div class="count-wrap"
                                            v-for="(count, index) in boStepConfig[item.label].hunterBanNumber"
                                            :key="`hunBan-${index}`">
                                            <div class="count_item" @mouseenter="showIcon = `hunter_${index}`"
                                                @mouseleave="showIcon = null">
                                                <n-icon :size="16" color="#9d9a9b" v-show="count">
                                                    <LockClosed />
                                                </n-icon>
                                                <div class="delete-overlay" v-show="showIcon === `hunter_${index}`"
                                                    @click.stop="removeBoNumberCount('hunterBanNumber', index)">
                                                    <n-icon :size="20" color="#ff4d4f">
                                                        <Close />
                                                    </n-icon>
                                                </div>
                                            </div>
                                            <n-icon :size="16" @click="changeLock('hunterBanNumber', index)"
                                                v-show="!disForm">
                                                <LockClosed v-if="count" />
                                                <LockOpen v-else="!count" />
                                            </n-icon>
                                        </div>
                                        <n-button strong secondary circle type="info"
                                            @click="addBoNumberCount('hunterBanNumber')">
                                            <template #icon>
                                                <n-icon>
                                                    <Add />
                                                </n-icon>
                                            </template>
                                        </n-button>
                                    </div>
                                </n-form-item-gi>
                                <n-form-item-gi :span="12" :label="$t('label.survivorBanNumber')" path="title">
                                    <div class="count_container">
                                        <div class="count-wrap"
                                            v-for="(count, index) in boStepConfig[item.label].survivorBanNumber"
                                            :key="`surBan-${index}`">
                                            <div class="count_item" @mouseenter="showIcon = `survivor_${index}`"
                                                @mouseleave="showIcon = null">
                                                <n-icon :size="16" color="#9d9a9b" v-show="count">
                                                    <LockClosed />
                                                </n-icon>
                                                <div class="delete-overlay" v-show="showIcon === `survivor_${index}`"
                                                    @click.stop="removeBoNumberCount('survivorBanNumber', index)">
                                                    <n-icon :size="20" color="#ff4d4f">
                                                        <Close />
                                                    </n-icon>
                                                </div>
                                            </div>
                                            <n-icon :size="16" @click="changeLock('survivorBanNumber', index)"
                                                v-show="!disForm">
                                                <LockClosed v-if="count" />
                                                <LockOpen v-else="!count" />
                                            </n-icon>
                                        </div>
                                        <n-button strong secondary circle type="info"
                                            @click="addBoNumberCount('survivorBanNumber')">
                                            <template #icon>
                                                <n-icon>
                                                    <Add />
                                                </n-icon>
                                            </template>
                                        </n-button>
                                    </div>
                                </n-form-item-gi>
                            </n-grid>
                            <n-grid :cols="24" :x-gap="24">
                                <n-form-item-gi :span="12" :label="$t('label.globalSurBanCount')" path="title">
                                    <h4 class="high-light"
                                        :class="survivorGlobalBpTotalComputed > MAX_SURVIVOR_BAN ? 'warning' : ''">
                                        {{ survivorGlobalBpTotalComputed }}
                                        <span class="warning"
                                            v-show="survivorGlobalBpTotalComputed > MAX_SURVIVOR_BAN">(已超出最大全局ban位数量)</span>
                                    </h4>
                                </n-form-item-gi>
                                <n-form-item-gi :span="12" :label="$t('label.globalHunBanCount')" path="title">
                                    <h4 class="high-light"
                                        :class="hunterGlobalBpTotalComputed > MAX_HUNTER_BAN ? 'warning' : ''">
                                        {{ hunterGlobalBpTotalComputed }}
                                        <span class="warning"
                                            v-show="hunterGlobalBpTotalComputed > MAX_HUNTER_BAN">(已超出最大全局ban位数量)</span>
                                    </h4>
                                </n-form-item-gi>
                            </n-grid>
                        </n-form>
                    </n-card>
                    <n-steps vertical v-if="rulesOptions[chooseBo] && rulesOptions[chooseBo].length > 0">
                        <n-step v-for="(step, index) in rulesOptions[chooseBo]">
                            <template #title>
                                <section class="title_wrap">
                                    <p>{{ step.title }}</p>
                                    <n-icon :size="18" @click="handleDeleteStep(index)" v-show="!disForm">
                                        <CloseSharp />
                                    </n-icon>
                                </section>
                            </template>
                            <n-card>
                                <n-form :ref="`${chooseBo}_step_${index}`" :rules :model="step" size="small"
                                    label-placement="top">
                                    <n-grid :cols="24" :x-gap="24">
                                        <n-form-item-gi :span="12" :label="$t('label.ruleTitle')" path="title">
                                            <n-input :disabled="disForm" v-model:value="step.title"
                                                placeholder="Input Title" />
                                        </n-form-item-gi>
                                        <n-form-item-gi :span="12" :label="$t('label.ruleExcutor')" path="excutor">
                                            <n-select :disabled="disForm" v-model:value="step.excutor"
                                                :options="excutorOptions" placeholder="Select Excutor Team" />
                                        </n-form-item-gi>
                                    </n-grid>
                                    <n-grid :cols="24" :x-gap="24">
                                        <n-form-item-gi :span="12" :label="$t('label.ruleTask')" path="task">
                                            <n-select :disabled="disForm" v-model:value="step.task"
                                                :options="ruleTaskOptions" placeholder="Select Rule Task" />
                                        </n-form-item-gi>
                                        <n-form-item-gi :span="12" :label="$t('label.ruleBindKey')" path="bindKey">
                                            <n-select :disabled="disForm" v-model:value="step.bindKey" multiple
                                                :options="computedDanymicOptions(step.excutor, step.task)"
                                                placeholder="Select Bind Value" />
                                        </n-form-item-gi>
                                    </n-grid>
                                    <n-grid :cols="24" :x-gap="24">
                                        <n-form-item-gi :span="12" :label="$t('label.ruleBindKeyLength')"
                                            path="excuteNumber">
                                            <n-input-number style="width:100%" :value="step.bindKey.length" disabled />
                                        </n-form-item-gi>
                                        <n-form-item-gi :span="12" :label="$t('label.componentType')"
                                            path="componentType">
                                            <n-select :disabled="disForm" v-model:value="step.componentType"
                                                :options="componentTypeOptions"
                                                placeholder="Select Excutor Component" />
                                        </n-form-item-gi>
                                    </n-grid>
                                    <n-grid :cols="24" :x-gap="24">
                                        <n-form-item-gi :span="12" :label="$t('label.optionsKey')" path="optionsKey">
                                            <n-select :disabled="disForm || step.componentType !== 'select'"
                                                v-model:value="step.optionsKey" :options="optionsKeyOptions"
                                                placeholder="Choose Selector Options" />
                                        </n-form-item-gi>
                                        <n-form-item-gi :span="12" :label="$t('label.globalBanType')">
                                            <n-switch :round="false" :disabled="disForm || step.task !== 'pick'"
                                                v-model:value="step.isInGlobalBan" />
                                        </n-form-item-gi>
                                    </n-grid>
                                    <n-grid :cols="24" :x-gap="24">
                                        <n-form-item-gi :span="12" :label="$t('label.taskSeniar')" path="taskSeniar">
                                            <n-input v-model:value="step.taskSeniar" placeholder="Input Seniar"
                                                disabled />
                                        </n-form-item-gi>
                                        <n-form-item-gi :span="12" :label="$t('label.animationKey')"
                                            path="showWaitAnimation">
                                            <n-select :disabled="disForm" v-model:value="step.showWaitAnimation"
                                                multiple :options="showAnimationOptions"
                                                placeholder="Select Animation" />
                                        </n-form-item-gi>
                                    </n-grid>
                                </n-form>
                            </n-card>
                        </n-step>
                    </n-steps>
                    <n-empty v-else :description="$t('text.noDate')">
                    </n-empty>
                </n-tab-pane>
                <template #suffix>
                    <n-button-group size="small" v-show="!disForm">
                        <n-button type="info" ghost size="small" @click="handleExportJson">
                            <template #icon>
                                <n-icon>
                                    <CloudDownload />
                                </n-icon>
                            </template>
                            {{ $t('button.export') }}
                        </n-button>
                        <n-button type="info" ghost size="small" @click="handleImportJson">
                            <template #icon>
                                <n-icon>
                                    <CloudUpload />
                                </n-icon>
                            </template>
                            {{ $t('button.import') }}
                        </n-button>
                        <n-button @click="addNewStep" strong secondary type="info">
                            <template #icon>
                                <n-icon>
                                    <AddSharp />
                                </n-icon>
                            </template>
                            {{ $t('button.step') }}
                        </n-button>
                        <n-button @click="saveAllRules" type="primary" size="small">
                            <template #icon>
                                <n-icon>
                                    <ArchiveSharp />
                                </n-icon>
                            </template>
                            {{ $t('button.save') }}
                        </n-button>
                    </n-button-group>
                </template>
            </n-tabs>
        </section>
    </div>
    <AddNewRuleModal v-model="isModalVisible" @finish="createRuleTitle" />
    <AddNewTabModal v-model="isTabModalVisible" @finish="createNewTab" />
</template>

<script setup lang='ts' name="RuleIndex">
import {
    Add,
    ChevronBackOutline,
    ColorWandSharp,
    TrashSharp,
    AddSharp,
    ArchiveSharp,
    CloseSharp,
    LockClosed,
    LockOpen,
    Close,
    CloudDownload,
    CloudUpload
} from '@vicons/ionicons5';
import storeHelper from '@/utils/TauriStore';
import AddNewRuleModal from '@/views/rulesPages/AddNewRuleModal.vue';
import AddNewTabModal from '@/views/rulesPages/AddNewTabModal.vue';
import { useDialog, useMessage } from 'naive-ui';
import {
    normalRules,
    ruleTaskOptions,
    bindKeyOptions,
    componentTypeOptions,
    optionsKeyOptions,
    excutorOptions,
    showAnimationOptions,
    normalStepConfig,
    BOStepConfig
} from '@/common/nomalRules.ts';
import { OptionRuleConfig } from '@/views/createGame/generator.ts';
import { save, open, ask } from '@tauri-apps/plugin-dialog';
import { readTextFile } from '@tauri-apps/plugin-fs';
import { invoke } from '@tauri-apps/api/core';

// 定义软编码
const MAX_SURVIVOR_BAN = 9;
const MAX_HUNTER_BAN = 3;
// 接口定义
interface RuleList {
    id: string;
    name: string;
}
interface RuleOptions {
    [key: string]: OptionRuleConfig[];
}

interface StepBo {
    label: keyof RuleOptions;
    value: keyof RuleOptions;
}
type LockIconKey = 'hunterBanNumber' | 'survivorBanNumber';
type BoKey = keyof RuleOptions;
const showIcon = ref<string | null>(null);
const message = useMessage();
const dialog = useDialog();
const chooseRuleId = ref<null | string>(null);
const ruleList = ref<RuleList[]>([]);
const isModalVisible = ref(false); //新增规则弹窗
const isTabModalVisible = ref(false); //新增标签弹窗
const dynamicBindKeyOptions = ref(bindKeyOptions); //动态绑定值
const disForm = computed(() => {
    return chooseRuleId.value === null;
})
// 规则配置
const rulesOptions = ref<RuleOptions>({
    'bo1': [],
    'bo2': [],
    'bo3': [],
    'bo4': [],
    'bo5': [],
    'bo5加赛': []
});
// bo配置
const boStepConfig = ref<BOStepConfig>(normalStepConfig)
const rules = {
    'title': [{ required: true, message: '请输入标题' }],
    'task': [{ required: true, message: '请选择任务' }],
    'excutor': [{ required: true, message: '请选择执行队伍' }],
    'bindKey': [{ required: true, message: '请选择绑定值' }],
    'optionsKey': [{ required: true, message: '请选择选择器选项' }],
    'taskSeniar': [{ required: true, message: '请输入执行顺序' }],
    'showWaitAnimation': [{ required: false, message: '请选择动画' }],
    'componentType': [{ required: true, message: '请选择组件类型' }],
    'excuteNumber': [{ required: false, message: '请输入执行次数' }],
    'id': [{ required: false, message: '请输入id' }]
}
const router = useRouter();
const stepBoArray = ref<StepBo[]>([]);
const chooseBo = ref<BoKey>('bo1');

// 计算全局bp
const survivorGlobalBpTotalComputed = computed(() => {
    let count = 0;
    for (const key in rulesOptions.value) {
        if (Object.prototype.hasOwnProperty.call(rulesOptions.value, key)) {
            const element = rulesOptions.value[key];
            element.forEach(ele => {
                if (ele.excutor === 'survivor' && ele.task === 'pick' && ele.isInGlobalBan) {
                    count += ele.bindKey.length;
                }
            });
        }
        if (chooseBo.value === key) {
            break;
        }
    }
    return count;
});
const hunterGlobalBpTotalComputed = computed(() => {
    let count = 0;
    for (const key in rulesOptions.value) {
        if (Object.prototype.hasOwnProperty.call(rulesOptions.value, key)) {
            const element = rulesOptions.value[key];
            element.forEach(ele => {
                if (ele.excutor === 'hunter' && ele.task === 'pick' && ele.isInGlobalBan) {
                    count += ele.bindKey.length;
                }
            });
        }
        if (chooseBo.value === key) {
            break;
        }
    }
    return count;
})
const _init = async () => {
    try {
        const ruleListData = await storeHelper.get('ruleList');
        ruleList.value = ruleListData ?? [];
        const useRule = await storeHelper.get('use_rule');
        chooseRuleId.value = useRule ?? null;
    } catch (error) {
        message.error('获取规则列表失败');
    }
};
// 使用规则
const useRulesMessage = () => {
    dialog.warning({
        title: '警告',
        content: `您确定应用规则id为${chooseRuleId.value || '<默认规则>'}的规则吗？`,
        positiveText: '确定',
        negativeText: '不确定',
        draggable: true,
        onPositiveClick: () => {
            storeHelper.set('use_rule', chooseRuleId.value);
            storeHelper.set('use_step_config', boStepConfig.value);
            message.success('已应用规则');
        },
        onNegativeClick: () => {
            message.error('取消！')
        }
    })
};
// 删除规则
const handleDeleteRule = (id: string, index: number) => {
    if (chooseRuleId.value === id) {
        return message.error('删除失败，不能删除目前应用的规则！');
    }
    dialog.warning({
        title: '警告',
        content: `您确定删除规则id为${id}的规则吗？`,
        positiveText: '确定',
        negativeText: '不确定',
        draggable: true,
        onPositiveClick: () => {
            ruleList.value.splice(index, 1);
            storeHelper.delete(`boStepConfig_${id}`);
            storeHelper.delete(`ruleOptions_${id}`);
            storeHelper.set('ruleList', ruleList.value);
            storeHelper.set('use_rule', null); //删除规则改成应用默认规则
            message.success('已删除规则，将自动应用默认规则！');
        },
        onNegativeClick: () => {
            message.error('取消！')
        }
    })
}
const createRuleTitle = (value: RuleList) => {
    ruleList.value.push(value);
    isModalVisible.value = false;
    storeHelper.set('ruleList', ruleList.value);
}
const openNewRuleModal = () => {
    if (ruleList.value.length >= 2) {
        return message.error('最多只能创建2条规则！');
    }
    isModalVisible.value = true;
}
onMounted(() => {
    _init();
});
watch(() => chooseRuleId.value, async (newVal) => {
    if (newVal === null) {
        rulesOptions.value = normalRules;
        boStepConfig.value = normalStepConfig;
    } else {
        const rules = await storeHelper.get(`ruleOptions_${newVal}`);
        const stepConfig = await storeHelper.get(`boStepConfig_${newVal}`);
        rulesOptions.value = rules ?? {};
        boStepConfig.value = stepConfig ?? {}
    }
    stepBoArray.value = [];
    if (Object.keys(rulesOptions.value).length > 0) {
        for (const key in rulesOptions.value) {
            if (Object.prototype.hasOwnProperty.call(rulesOptions.value, key)) {
                stepBoArray.value.push({
                    label: key,
                    value: key
                })
            }
        }
        chooseBo.value = stepBoArray.value[0]?.value || 'bo1'
    }
}, {
    immediate: true
});
watch(() => boStepConfig.value[chooseBo.value], (newVal) => {
    if (Object.keys(boStepConfig.value).length === 0 || !newVal) return;
    dynamicBindKeyOptions.value = []; //动态绑定值
    bindKeyOptions.forEach(item => {
        dynamicBindKeyOptions.value.push(item);
    })
    newVal.hunterBanNumber.filter(item => !Boolean(item)).forEach((_, index) => {
        dynamicBindKeyOptions.value.push({
            label: `禁用监管者${index + 1}`,
            value: `banHun${index + 1}`,
        })
    })
    newVal.survivorBanNumber.filter(item => !Boolean(item)).forEach((_, index) => {
        dynamicBindKeyOptions.value.push({
            label: `禁用求生者${index + 1}`,
            value: `banSur${index + 1}`
        })
    })
}, { immediate: true, deep: true });

// 计算下拉框
const computedDanymicOptions = computed(() => {
    return (type: string, task: 'pick' | 'ban') => {
        let replaceString = '';
        if (type === 'hunter') {
            replaceString = task === 'pick' ? 'pickHun' : 'banSur';
        } else {
            replaceString = task === 'pick' ? 'pickSur' : 'banHun';
        }
        return dynamicBindKeyOptions.value.filter(item => item.value.includes(replaceString))
            .map(item => {
                return {
                    label: item.label,
                    value: item.value
                }
            });
    }

})
// 添加新步骤
const addNewStep = () => {
    if (rulesOptions.value[chooseBo.value] && Array.isArray(rulesOptions.value[chooseBo.value])) {
        rulesOptions.value[chooseBo.value].push({
            id: (rulesOptions.value[chooseBo.value].length + 1).toString(),
            title: '自定义标题',
            task: 'pick',
            excuteNumber: 0,
            excutor: 'hunter',
            bindKey: [],
            showWaitAnimation: [],
            taskSeniar: rulesOptions.value[chooseBo.value].length + 1,
            optionsKey: 'surHalf',
            componentType: 'select',
            isInGlobalBan: false
        })
    } else {
        message.error('请先选择一个BO场次');
    }
}
// 校验是否能够通过最大ban位数量
const isExceedMaxGlobalBanCount = () => {
    return survivorGlobalBpTotalComputed.value > MAX_SURVIVOR_BAN || hunterGlobalBpTotalComputed.value > MAX_HUNTER_BAN;
}
// 保存规则
const saveAllRules = async () => {
    try {
        if (isExceedMaxGlobalBanCount()) {
            return message.error('保存失败，配置规则流程超出最大全局ban位数量！');
        }
        await storeHelper.set(`boStepConfig_${chooseRuleId.value}`, boStepConfig.value);
        await storeHelper.set(`ruleOptions_${chooseRuleId.value}`, rulesOptions.value);
        message.success('保存成功');
    } catch (error) {
        message.error('保存失败');
    }
}

// 删除节点
const handleDeleteStep = (index: number) => {
    dialog.warning({
        title: '警告',
        content: `您确定删除步骤${index + 1}的节点吗？`,
        positiveText: '确定',
        negativeText: '不确定',
        draggable: true,
        onPositiveClick: () => {
            rulesOptions.value[chooseBo.value].splice(index, 1);
            message.success('删除成功');
        },
        onNegativeClick: () => {
            message.error('取消！')
        }
    })
}

// 新增tab
const addNewTab = () => {
    if (isExceedMaxGlobalBanCount()) {
        return message.error('无法新增流程，配置规则流程已经超出最大全局ban位数量！');
    }
    if (stepBoArray.value.length === 11) {
        return message.error('最多只能添加11个BO环节！');
    }
    isTabModalVisible.value = true;
}

// 创建新标签
const createNewTab = (name: string) => {
    if (stepBoArray.value.findIndex(item => item.label === name) !== -1) {
        return message.error('该标签已存在，请更换名称！');
    }
    stepBoArray.value.push({
        label: name,
        value: name
    });
    chooseBo.value = stepBoArray.value[0]?.value || 'bo1';
    rulesOptions.value[name] = [];
    boStepConfig.value[name] = {
        chooseMap: true,
        banMap: true,
        hunterBanNumber: [true, true, true],
        survivorBanNumber: [false, false, false, false]
    }
    isTabModalVisible.value = false;
}

const closeTab = (name: string) => {
    dialog.warning({
        title: '警告',
        content: `您确定删除步骤${name}的赛程节点吗，一旦删除配置的规则将无法恢复？`,
        positiveText: '确定',
        negativeText: '不确定',
        draggable: true,
        onPositiveClick: () => {
            const nameIndex = stepBoArray.value.findIndex(item => item.value === name);
            stepBoArray.value.splice(nameIndex, 1);
            Reflect.deleteProperty(rulesOptions.value, name);
            Reflect.deleteProperty(boStepConfig.value, name);
            chooseBo.value = stepBoArray.value[0]?.value || 'bo1';
            message.success('删除成功');
        },
        onNegativeClick: () => {
            message.error('取消！')
        }
    })

}

// 改变童锁
const changeLock = (key: LockIconKey, index: number) => {
    if (disForm.value) return;
    boStepConfig.value[chooseBo.value][key][index] = !boStepConfig.value[chooseBo.value][key][index]
}
// 添加
const addBoNumberCount = (key: LockIconKey) => {
    if (disForm.value) return message.warning('无法新增默认规则的ban位！');
    if (boStepConfig.value[chooseBo.value][key].length >= 8) {
        return message.error('最多只能添加七个ban位');
    }
    boStepConfig.value[chooseBo.value][key].push(false);
}
// 删除ban位
const removeBoNumberCount = (key: LockIconKey, index: number) => {
    if (disForm.value) return message.warning('无法删除默认规则的ban位！');
    boStepConfig.value[chooseBo.value][key].splice(index, 1);
}
// 处理导出
const handleExportJson = async () => {
    try {
        const dataToExport = {
            rulesOptions: rulesOptions.value,
            boStepConfig: boStepConfig.value
        }
        // 1. 弹出保存对话框让用户选择位置
        const filePath = await save({
            title: "保存JSON文件",
            defaultPath: `${chooseRuleId.value}规则.json`,
            filters: [{
                name: "JSON",
                extensions: ["json"]
            }]
        });

        if (!filePath) {
            return;
        }
        // 2. 调用Rust后端保存文件
        const result = await invoke<string>('export_to_json', {
            data: {
                data: dataToExport,
                file_path: filePath  // 传递用户选择的路径
            }
        });
        message.success('文件导出成功！');
        return result;
    } catch (error) {
        message.error('文件保存失败！');
        throw error;
    }
}

// 检验是否有JSON数据
const hasCompleteRaw = (obj: Object) => {
    if (!obj) return false;
    if ('rulesOptions' in obj && 'boStepConfig' in obj) return true;
    return false;
}
// 处理导入
const handleImportJson = async () => {
    try {
        const answer = await ask('导入JSON规则将覆盖现有的规则数据，请问是否继续?', {
            title: '警告',
            kind: 'warning',
        });
        if (!answer) throw new Error('取消');
        const file = await open({
            multiple: false,
            directory: false,
            filters: [{ name: 'JSON', extensions: ['json'] }]
        });
        if (!file) throw new Error('文件不存在！');
        const content = await readTextFile(file);
        const jsonData = JSON.parse(content);
        if (!hasCompleteRaw(jsonData)) throw new Error('JSON数据不符合格式要求！');
        const { rulesOptions: jsonRules, boStepConfig: jsonConfig } = jsonData;
        rulesOptions.value = jsonRules;
        boStepConfig.value = jsonConfig;
        if (Object.keys(rulesOptions.value).length > 0) {
            stepBoArray.value = [];
            for (const key in rulesOptions.value) {
                if (Object.prototype.hasOwnProperty.call(rulesOptions.value, key)) {
                    stepBoArray.value.push({
                        label: key,
                        value: key
                    })
                }
            }
            chooseBo.value = stepBoArray.value[0]?.value || 'bo1'
        }
        message.success('导入成功，已覆盖规则!');
    } catch (error) {
        message.error(error instanceof Error ? error.message : '未知错误！');
    }
}
</script>

<style scoped lang='scss'>
@use 'sass:color';
$border-active-c: #4090EF;
$border-c: #D7D7D7;

// 父容器
.main_info {
    @include useTheme {
        background: getVar('rawBg');
    }
}

header {
    padding: 0.5em;
    display: flex;
    align-items: center;
    justify-content: space-between;
    flex-wrap: wrap;

    .rule_section {
        display: flex;
        align-items: center;
        justify-content: center;
        gap: 1em;

        .rule_item--wrap {
            padding: 0.5em 1em;
            border-radius: 12px;
            border: 1px solid $border-c;
            cursor: pointer;
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 0.2em;
            font-size: 0.8em;
            text-overflow: ellipsis;
            overflow: hidden;
            white-space: nowrap;
            width: calc(100px - 2em);
            flex-grow: 0;
            flex-shrink: 0;
            transition: all 0.3s ease;

            @include useTheme {
                color: getVar('text');
            }

            &:hover,
            &.active {
                border-color: $border-active-c;
                background: lighten($border-active-c, 20%);
            }

        }
    }

}

.rule_setting {
    padding: 0.5em;

    .title_wrap {
        display: flex;
        align-items: center;
        gap: 0.5em;

        i {
            color: #f40;
            font-weight: bolder;
            cursor: pointer;

            &:hover {
                color: lighten(#f40, 20%)
            }
        }
    }

    // 卡片样式
    .card_container {
        margin: 1em 0;
    }
}

// 锁屏样式
.count_container {
    display: flex;
    align-items: center;
    gap: 10px;
    width: 100%;
    overflow: hidden;
    flex-wrap: wrap;

    .count-wrap {
        display: flex;
        flex-direction: column;
        align-items: center;
        gap: 5px;
        cursor: pointer;

        .count_item {
            width: 32px;
            height: 32px;
            border: 2px solid #9d9a9b;
            box-sizing: border-box;
            display: flex;
            align-items: center;
            justify-content: center;
            background: #010000;
            border-radius: 2px;
            position: relative;

            .delete-overlay {
                position: absolute;
                top: 0;
                left: 0;
                right: 0;
                bottom: 0;
                background-color: rgba(194, 194, 194, 0.5);
                display: flex;
                align-items: center;
                justify-content: center;
                border-radius: 4px;
                /* 根据你的实际样式调整 */
            }
        }
    }

}

.high-light.warning {
    color: #f40;

    .warning {
        color: #f40;
    }
}
</style>